package pub.wkq.bo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import pub.wkq.common.exception.CustomException;
import pub.wkq.common.result.ResponseStatusEnum;
import pub.wkq.common.utils.MD5Utils;
import pub.wkq.pojo.ar.AdminAR;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;

/**
 * 重置密码的 BO
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResetPwdBO {
    @NotBlank(message = "管理员账号不能为空")
    private String adminId;
    @NotBlank(message = "密码不能为空")
    private String password;
    @NotBlank(message = "确认密码不能为空")
    private String rePassword; // 新密码

    public void modifyPwd() {
        //校验
        validate();
        //重置密码
        //生成随机数字或者英文字母结合的盐
        String slat = (int) (Math.random() * 9 + 1) * 100000 + "";
        String pwd = MD5Utils.encrypt(password, slat);
        AdminAR adminAR = new AdminAR();
        adminAR.setId(adminId);
        adminAR.setPassword(pwd);
        adminAR.setSlat(slat);
        adminAR.setUpdatedTime(LocalDateTime.now());
        adminAR.updateById();
    }

    private void validate() {
        checkPwd();
        checkAdminId();
    }

    private void checkAdminId() {
        if (StringUtils.isBlank(adminId)) {
            throw new CustomException(ResponseStatusEnum.ADMIN_USERNAME_NULL_ERROR);
        }
        AdminAR adminAR = new AdminAR();
        adminAR.setId(adminId);
        adminAR = adminAR.selectById();
        if (adminAR == null) {
            throw new CustomException(ResponseStatusEnum.ADMIN_USERNAME_NULL_ERROR);
        }
    }

    private void checkPwd() {
        //不为空,两次密码一致
        if (StringUtils.isBlank(password) || StringUtils.isBlank(rePassword) || !password.equals(rePassword)) {
            throw new CustomException(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
        }
        //密码必须是包含字母、数字、特殊符号，并且必须有一个大写字母
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}\\[\\]:\";'<>?,.\\/]).{8,}$";
        if (!password.matches(regex)) {
            throw new CustomException(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
        }
    }
}
